package com.cloud.netty;

import com.cloud.utils.ByteUtil;
import io.netty.buffer.ByteBufUtil;

import java.math.BigInteger;

/**
 * @program: netty
 * @description:
 * @author: Cloud
 * @create: 2021/12/8 13:46:57
 */
public class Test {

    /**
     * 计算CRC16校验码
     *
     * @param bytes
     * @return
     */
    public static String getCRC16(byte[] bytes) {
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        return Integer.toHexString(CRC);
    }

    public static void main(String[] args) {
        String s1 = "01 03 00 00 00 01";
        String crc = getCRC16(ByteUtil.hex2byte(s1));
        System.out.println("crc = " + crc);
    }
}
